package RateService

import (
	RateModel "blog/app/models/rate_model"
	"blog/config"
	"blog/service"
	"blog/utils"
	"blog/utils/tools"
	"fmt"
	"github.com/gin-gonic/gin"
	"strconv"
)

// GetRateByDateTimeseries 提供接口按日期获取汇率数据
func GetRateByDateTimeseries(c *gin.Context) {
	startDate := c.Query("start_date")
	endDate := c.Query("end_date")
	var data []RateModel.RateRecord

	err := utils.MySqlDB.Model(&RateModel.RateRecord{}).
		Where("rate_date >= ? and rate_date < ?", startDate, endDate).
		Order("rate_date desc").
		Find(&data)
	if err.Error != nil {
		fmt.Println(err)
	}
	// 把数组抽出来成为map
	dataMap := tools.SliceToGroupMap(data, func(r *RateModel.RateRecord) string {
		rateDateStr := tools.FormatToDate(r.RateDate)
		return rateDateStr
	})
	var mainMap = make(map[string]map[string]float64)
	for index, item := range dataMap {
		var subMap = make(map[string]float64)
		for _, subItem := range item {
			subMap[subItem.ToCode], _ = strconv.ParseFloat(subItem.Rate, 64)
		}
		mainMap[index] = subMap
	}
	service.CommonCJsonReply(c, config.SUCCESS, mainMap)
}

// GetRawData 返回原始数据
func GetRawData(c *gin.Context) {
	startDate := c.Query("start_date")
	endDate := c.Query("end_date")
	var data []RateModel.RateRecord
	err := utils.MySqlDB.Model(&RateModel.RateRecord{}).
		Where("rate_date >= ? and rate_date < ?", startDate, endDate).
		Order("rate_date desc").
		Find(&data)
	if err.Error != nil {
		fmt.Println(err)
	}
	service.CommonCJsonReply(c, config.SUCCESS, data)
}
